package com.service.layui.impl;

import java.util.ArrayList;
import java.util.List;

import com.dao.ProductLayuiDao;
import com.entity.Layui;
import com.entity.Product;
import com.entity.ProductCategory;
import com.entity.ProductVo;
import com.service.layui.LayuiService;
import com.utils.MybatisUtil;
import com.utils.Pager;

public class LayuiServiceImpl implements LayuiService{

	/**
	 * 	分页查询所有商品
	 */
	@Override
	public List<Product> finProduct(Pager page) {
		ProductLayuiDao layui = MybatisUtil.getMapper(ProductLayuiDao.class);
		List<Product> pageProLayui = layui.pageProLayui(page);
		MybatisUtil.closeCommit();
		return pageProLayui;
	}

	/**
	 * 	查询分类名
	 */
	@Override
	public List<ProductCategory> finProductCategory() {
		ProductLayuiDao layui = MybatisUtil.getMapper(ProductLayuiDao.class);
		List<ProductCategory> productCategoryList = layui.productCategoryList();
		MybatisUtil.closeCommit();
		return productCategoryList;
	}

	/**
	 * 	处理分类名
	 */
	@Override
	public List<ProductVo> ProductVoList(Pager page) {
		List<ProductVo> provoList = new ArrayList<ProductVo>();
		List<Product> proList = finProduct(page);
		List<ProductCategory> cateList = finProductCategory();
		for(Product pro : proList) {
			ProductVo provo = new ProductVo();
			provo.setId(pro.getId());
			provo.setName(pro.getName());
			provo.setDescription(pro.getDescription());
			provo.setPrice(pro.getPrice());
			provo.setStock(pro.getStock());
			provo.setFileName(pro.getFileName());
			for(ProductCategory cate : cateList) {
				if(pro.getCategoryLevel1() == cate.getId()) {
					provo.setCategoryLevel1(cate.getName());
				}
				if(pro.getCategoryLevel2() == cate.getId()) {
					provo.setCategoryLevel2(cate.getName());
				}
				if(pro.getCategoryLevel3() == cate.getId()) {
					provo.setCategoryLevel3(cate.getName());
				}
				if(provo.getCategoryLevel1() != null && provo.getCategoryLevel2() != null && provo.getCategoryLevel3() != null) {
					break;
				}
			}
			provoList.add(provo);
		}
		return provoList;
	}

	/**
	 * 	分页查询,返回Layui格式数据
	 */
	@Override
	public Layui returnLayui(Pager page) {
		ProductLayuiDao la = MybatisUtil.getMapper(ProductLayuiDao.class);
		int productCount = la.productCount();
		List<ProductVo> productVoList = ProductVoList(page);
		Layui layui = new Layui();
		layui.setCode(0);
		layui.setMsg("");	
		layui.setCount(productCount);	//总数
		layui.setData(productVoList);
		MybatisUtil.closeCommit();
		return layui;
	}

}

